package data

import (
	"context"

	"gitee.com/shuokeyun/kratos/errors"
	"gitee.com/shuokeyun/merchant-service/internal/data/ent"
	"gitee.com/shuokeyun/merchant-service/internal/domain"
)

var _ domain.MerchantRepo = (*merchantRepo)(nil)

type merchantRepo struct {
	client                *ent.Client
	merchant              *ent.MerchantClient
	merchantCertification *ent.MerchantCertificationClient
	cache                 domain.MerchantCacheRepo
}

func NewMerchantRepo(client *ent.Client, cache domain.MerchantCacheRepo) domain.MerchantRepo {
	return &merchantRepo{
		client:                client,
		merchant:              client.Merchant,
		merchantCertification: client.MerchantCertification,
		cache:                 cache,
	}
}

func (m *merchantRepo) ListItems(ctx context.Context, search *domain.SearchMerchantList) ([]*domain.Merchant, int32, error) {
	//TODO implement me
	panic("implement me")
}

func (m *merchantRepo) GetItem(ctx context.Context, id int32, fields []string) (*domain.Merchant, error) {
	//var mFields, cFields []string
	//for _, filed := range fields {
	//	before, after, found := strings.Cut(filed, ".")
	//	if found {
	//		if before == "certification" {
	//			cFields = append(cFields, after)
	//		}
	//	} else {
	//		mFields = append(mFields, filed)
	//	}
	//}
	do, err := m.cache.GetMerchant(ctx, id)
	if err != nil {
		return nil, err
	}
	if do != nil {
		return do, nil
	}
	mPo, err := m.merchant.Get(ctx, int64(id))
	if err != nil {
		if ent.IsNotFound(err) {
			return nil, errors.ErrorRecordNotFound("merchant %d not fund", id)
		}
		return nil, errors.ErrorDBWrap(err, "select merchant error")
	}
	mcPo, err := m.merchantCertification.Get(ctx, int64(id))
	if err != nil {
		if !ent.IsNotFound(err) {
			return nil, errors.ErrorDBWrap(err, "select merchant_certification error")
		}
	}
	do = merchantPoConvDo(mPo, mcPo)
	return do, m.cache.SetMerchant(ctx, do)
}

func (m *merchantRepo) CreateItem(ctx context.Context, do *domain.Merchant) (*domain.Merchant, error) {
	//TODO implement me
	panic("implement me")
}

func (m *merchantRepo) UpdateItem(ctx context.Context, do *domain.Merchant, fields []string) (*domain.Merchant, error) {
	//TODO implement me
	panic("implement me")
}
